package com.taorenqi.business.fragment.mine;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.taorenqi.business.R;
import com.taorenqi.business.adapter.MoneyDetailAdapter;
import com.taorenqi.business.adapter.PopularityAdapter;
import com.taorenqi.business.app.MyApp;
import com.taorenqi.business.fragment.base.BaseBackFragment;
import com.taorenqi.business.utils.Encoder;
import com.taorenqi.business.widget.statusview.StatusView;
import com.taorenqi.business.widget.subscribers.PageDataSubscriberOnNext;
import com.taorenqi.business.widget.subscribers.ProgressSubscriber;
import com.taorenqi.data.common.BasePageableResponse;
import com.taorenqi.data.entity.mine.MoneyDetailEntity;
import com.taorenqi.data.entity.mine.PopularityEntity;
import com.taorenqi.data.service.HttpRequest;
import com.taorenqi.data.service.MineDataHttpRequest;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 人气值
 * A simple {@link Fragment} subclass.
 */
public class PopularityFragment extends BaseBackFragment implements BaseQuickAdapter.RequestLoadMoreListener,SpringView.OnFreshListener{


    @Bind(R.id.status_view)
    StatusView statusView;
    @Bind(R.id.money_detail_back)
    ImageView moneyDetailBack;
    @Bind(R.id.money_detail_title)
    TextView moneyDetailTitle;
    @Bind(R.id.money_detail_choose)
    TextView moneyDetailChoose;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.popularity_recyclerview)
    RecyclerView mRecyclerView;
    @Bind(R.id.popularity_springview)
    SpringView mSpringview;

    private Button dialogMoneyDetailAll;
    private Button dialogMoneyDetailRecharge;
    private Button dialogMoneyDetailRebate;
    private PopupWindow popupwindow;
    private String titleView = "";
    private int width;
    private int height;
    private boolean flag = true;
    private int page = 1;
    private int TOTAL_COUNTER = 0;
    private int mCurrentCounter = 0;
    private int type = 0;

    private BasePageableResponse<PopularityEntity> data;
    private PageDataSubscriberOnNext<BasePageableResponse<PopularityEntity>> subscriber;
    private List<PopularityEntity> list = new LinkedList<>();
    private PopularityAdapter mAdapter;
    public static PopularityFragment newInstance() {
        // Required empty public constructor
        PopularityFragment fragment = new PopularityFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_popularity, container, false);
        ButterKnife.bind(this, view);
        initToolbar();
        initView();
        initAdapter();
        initHttpRequestData();
        return attachToSwipeBack(view);
    }

    private void initView() {
        mSpringview.setType(SpringView.Type.FOLLOW);
        mSpringview.setHeader(new DefaultHeader(_mActivity));
        mSpringview.setListener(this);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    }

    private void initHttpRequestData() {
        subscriber = new PageDataSubscriberOnNext<BasePageableResponse<PopularityEntity>>() {
            @Override
            public void onNext(BasePageableResponse<PopularityEntity> entity) {
                data = entity;
                list = data.getDatalist();
                mSpringview.onFinishFreshAndLoad();

                if (mCurrentCounter == 0) {
                    mAdapter.setNewData(list);
                } else {
                    mAdapter.addData(list);
                }
                mCurrentCounter = mAdapter.getData().size();
                TOTAL_COUNTER = data.getCountData();
                Log.e("total",TOTAL_COUNTER + " ");
                mAdapter.loadMoreComplete();
            }

        };

        requestData(0,1);
    }


    //请求不同类型的资金明细，默认为
    private void requestData(int type,int page) {
        MineDataHttpRequest.getInstance(MyApp.getApp()).getPopularity(new ProgressSubscriber(subscriber, _mActivity), type, page, HttpRequest.DEFAULT_PAGE_SIZE);
    }

    private void initAdapter() {
        mAdapter = new PopularityAdapter(list);
        mAdapter.openLoadAnimation();
        mAdapter.setEnableLoadMore(true);
        mAdapter.setOnLoadMoreListener(this);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initToolbar() {
        moneyDetailTitle.setText("人气值明细");
        moneyDetailChoose.setText("筛选");
        DisplayMetrics metric = new DisplayMetrics();
        _mActivity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        width = metric.widthPixels;
        height = metric.heightPixels;
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.money_detail_back, R.id.money_detail_choose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.money_detail_back:
                break;
            case R.id.money_detail_choose:
                if (flag) {
                    initDialog();
                    flag = false;
                } else if (popupwindow != null) {
                    try {
                        popupwindow.dismiss();
                        popupwindow = null;
                        flag = true;
                    } catch (Exception e) {
                    }
                }

                break;
        }
    }

    private void initDialog() {
        View customView = LayoutInflater.from(_mActivity).inflate(R.layout.dialog_popularity, null, false);
        popupwindow = new PopupWindow(customView, width, height);
        popupwindow.setContentView(customView);
        popupwindow.showAsDropDown(toolbar, 2, 5);
        dialogMoneyDetailAll = customView.findViewById(R.id.dialog_money_detail_all);
        dialogMoneyDetailRecharge = customView.findViewById(R.id.dialog_money_detail_recharge);
        dialogMoneyDetailRebate = customView.findViewById(R.id.dialog_money_detail_rebate);

        if ("全部".equals(titleView)) {
            dialogMoneyDetailAll.setBackgroundResource(R.drawable.login_button);
            dialogMoneyDetailRecharge.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
            dialogMoneyDetailRebate.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
            dialogMoneyDetailAll.setTextColor(getResources().getColor(R.color.white));
            dialogMoneyDetailRecharge.setTextColor(getResources().getColor(R.color.colorPrimary));
            dialogMoneyDetailRebate.setTextColor(getResources().getColor(R.color.colorPrimary));
        } else if ("充值".equals(titleView)){
            dialogMoneyDetailAll.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
            dialogMoneyDetailRecharge.setBackgroundResource(R.drawable.login_button);
            dialogMoneyDetailRebate.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
            dialogMoneyDetailAll.setTextColor(getResources().getColor(R.color.colorPrimary));
            dialogMoneyDetailRecharge.setTextColor(getResources().getColor(R.color.white));
            dialogMoneyDetailRebate.setTextColor(getResources().getColor(R.color.colorPrimary));
        }else if ("其他".equals(titleView)){
            dialogMoneyDetailAll.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
            dialogMoneyDetailRecharge.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
            dialogMoneyDetailRebate.setBackgroundResource(R.drawable.login_button);
            dialogMoneyDetailAll.setTextColor(getResources().getColor(R.color.colorPrimary));
            dialogMoneyDetailRecharge.setTextColor(getResources().getColor(R.color.colorPrimary));
            dialogMoneyDetailRebate.setTextColor(getResources().getColor(R.color.white));
        }
        dialogMoneyDetailAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = 0;
                page = 1;
                dialogMoneyDetailAll.setBackgroundResource(R.drawable.login_button);
                dialogMoneyDetailRecharge.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
                dialogMoneyDetailRebate.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
                dialogMoneyDetailAll.setTextColor(getResources().getColor(R.color.white));
                dialogMoneyDetailRecharge.setTextColor(getResources().getColor(R.color.colorPrimary));
                dialogMoneyDetailRebate.setTextColor(getResources().getColor(R.color.colorPrimary));
                data.getDatalist().clear();
                mCurrentCounter = 0;
                requestData(type,page);
                mAdapter.setEnableLoadMore(true);
                mAdapter.removeAllFooterView();
                titleView = "全部";
                flag = true;
                popupwindow.dismiss();
//                mAdapter.notifyDataSetChanged();
            }
        });

        dialogMoneyDetailRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = 1;
                page = 1;
                dialogMoneyDetailAll.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
                dialogMoneyDetailRecharge.setBackgroundResource(R.drawable.login_button);
                dialogMoneyDetailRebate.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
                dialogMoneyDetailAll.setTextColor(getResources().getColor(R.color.colorPrimary));
                dialogMoneyDetailRecharge.setTextColor(getResources().getColor(R.color.white));
                dialogMoneyDetailRebate.setTextColor(getResources().getColor(R.color.colorPrimary));
                data.getDatalist().clear();
                mCurrentCounter = 0;
                requestData(type,page);
                mAdapter.setEnableLoadMore(true);
                mAdapter.removeAllFooterView();
                titleView = "充值";
                flag = true;
                popupwindow.dismiss();
                mAdapter.notifyDataSetChanged();
            }
        });

        dialogMoneyDetailRebate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = 2;
                page = 1;
                dialogMoneyDetailAll.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
                dialogMoneyDetailRecharge.setBackgroundResource(R.drawable.bg_btn_rectangle_money_detail);
                dialogMoneyDetailRebate.setBackgroundResource(R.drawable.login_button);
                dialogMoneyDetailAll.setTextColor(getResources().getColor(R.color.colorPrimary));
                dialogMoneyDetailRecharge.setTextColor(getResources().getColor(R.color.colorPrimary));
                dialogMoneyDetailRebate.setTextColor(getResources().getColor(R.color.white));
                data.getDatalist().clear();
                mCurrentCounter = 0;
                requestData(type,page);
                mAdapter.setEnableLoadMore(true);
                mAdapter.removeAllFooterView();
                titleView = "邀请返利";
                flag = true;
                popupwindow.dismiss();
                mAdapter.notifyDataSetChanged();
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (popupwindow != null) {
            try {
                popupwindow.dismiss();
                popupwindow = null;
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onRefresh() {
        mCurrentCounter = 0;
        requestData(type,1);
        mAdapter.setEnableLoadMore(true);
        mAdapter.removeAllFooterView();
    }

    @Override
    public void onLoadmore() {

    }

    @Override
    public void onLoadMoreRequested() {
        mRecyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mCurrentCounter >= TOTAL_COUNTER) {
                    mAdapter.loadMoreEnd();

                } else {
                    requestData(type,getCurrentPage());
                }
            }
        }, 200);
    }

    public int getCurrentPage() {
        return mCurrentCounter / HttpRequest.DEFAULT_PAGE_SIZE + 1;
    }
}
